package mysql

import (
	"fmt"
	"github.com/astaxie/beego"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"log"
	"strings"
	"time"
)

type MysqlConfig struct {
	UserName string
	Password string
	HostUrl  string
	Database string
	Alias    string
}

type DataMysqlSourceClinet struct {
	SqlDB *sqlx.DB
	Name  string
}

var DataSourceClientMap map[string]DataMysqlSourceClinet

func init() {
	log.Println("init datasource ...")
	DataSourceClient := make(map[string]DataMysqlSourceClinet)
	dbstr := beego.AppConfig.String("dblist")
	dblist := strings.Split(dbstr, ",")
	for _, item := range dblist {
		CnRalUserName := beego.AppConfig.String(item + ".username")
		CnRalPwd := beego.AppConfig.String(item + ".password")
		CnRalhost := beego.AppConfig.String(item + ".host")
		DbName := beego.AppConfig.String(item + ".dbname")

		if CnRalUserName == "" || CnRalPwd == "" || CnRalhost == "" || DbName == "" {
			log.Println("参数为空！", item)
			continue
			return
		}
		cn_real_config := MysqlConfig{
			UserName: CnRalUserName,
			Password: CnRalPwd,
			HostUrl:  CnRalhost,
			Database: DbName,
			Alias:    item,
		}
		// 从源数据库获取
		cn_real_client := NewMysqlClient(cn_real_config)
		DataSourceClient[item] = *cn_real_client
		log.Println(item + " inited!")
	}
	DataSourceClientMap = DataSourceClient
	log.Println("mysql client map初始化完成!", DataSourceClientMap)
}

func NewMysqlClient(config MysqlConfig) (*DataMysqlSourceClinet) {
	dbDSN := fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?charset=utf8",
		config.UserName, config.Password, config.HostUrl, config.Database)
	db, MysqlDbErr := sqlx.Open("mysql", dbDSN)
	if MysqlDbErr != nil {
		log.Println(MysqlDbErr)
	}
	db.SetMaxOpenConns(5)
	db.SetMaxIdleConns(1)
	db.SetConnMaxLifetime(100 * time.Second)

	if MysqlDbErr = db.Ping(); nil != MysqlDbErr {
		log.Println("数据库连接失败: " + MysqlDbErr.Error())
	}
	clinet := &DataMysqlSourceClinet{SqlDB: db, Name: config.Alias}
	return clinet
}

func GetDbResourceByCCid(Ccid string) (*DataMysqlSourceClinet) {
	if Ccid == "Frankfurt_dev" {
		clinet := DataSourceClientMap["eu_dev"]
		return &clinet
	} else if Ccid == "Frankfurt" {
		clinet := DataSourceClientMap["eu_real"]
		return &clinet
	} else if Ccid == "Hangzhou_dev" {
		clinet := DataSourceClientMap["cn_dev"]
		return &clinet
	} else {
		clinet := DataSourceClientMap["cn_real"]
		return &clinet
	}
}
